package com.example.chengzhong.controller;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.InputStream;
import java.text.SimpleDateFormat;

import gnu.io.*;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class SerialReader {

    public static void main(String[] args) throws Exception {
        // 初始化串口
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM1");
        SerialPort serialPort = (SerialPort) portIdentifier.open("SerialReader", 2000);
        serialPort.setSerialPortParams(1200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        InputStream input = serialPort.getInputStream();

        // 定时任务每秒读取一次
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    StringBuilder data = new StringBuilder();
                    int available = input.available();
                    if (available > 0) {
                        byte[] buffer = new byte[available];
                        int len = input.read(buffer);
                        data.append(new String(buffer, 0, len));
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                    String[] split = data.toString().split("\n");
                    String lastData = split[split.length - 1];
//                    lastData.matches("wn[0-9]{6}")
                    System.out.println(sdf.format(new Date()) + " | 数据: " + data + " | 数据2: " + lastData + "\n");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 0, 1000); // 延迟0ms，间隔1000ms（1秒）
    }
}

